/**
 * 百度智能云人脸识别API服务
 * 提供人脸检测、质量评估、特征提取等功能
 */

// 百度人脸识别API配置
const BAIDU_FACE_CONFIG = {
  // 你的API Key
  API_KEY: 'ITjcecbrjKJoRe24r3njJVXI',
  // 你的Secret Key
  SECRET_KEY: '5yRlKjMs2JJK3sH4vSaGpZLCFCvrNWjk',
  // 人脸检测API地址（通过代理）
  DETECT_URL: '/baidu-face/rest/2.0/face/v3/detect',
  // 人脸比对API地址（通过代理）
  MATCH_URL: '/baidu-face/rest/2.0/face/v3/match',
  // 人脸搜索API地址（通过代理）
  SEARCH_URL: '/baidu-face/rest/2.0/face/v3/multi-search',
  // 人脸库管理API地址（通过代理）
  FACE_SET_URL: '/baidu-face/rest/2.0/face/v3/faceset',
  // 人脸库用户管理API地址（通过代理）
  FACE_USER_URL: '/baidu-face/rest/2.0/face/v3/faceset/user',
  // 人脸（单张）管理相关API前缀（通过代理）
  FACE_FACE_URL: '/baidu-face/rest/2.0/face/v3/faceset/face',
  // Access Token获取地址（通过代理）
  TOKEN_URL: '/baidu-face/oauth/2.0/token'
}

// 人脸质量检测阈值配置
const QUALITY_THRESHOLDS = {
  // 遮挡阈值
  occlusion: {
    left_eye: 0.6,      // 左眼被遮挡的阈值
    right_eye: 0.6,     // 右眼被遮挡的阈值
    nose: 0.7,          // 鼻子被遮挡的阈值
    mouth: 0.7,         // 嘴巴被遮挡的阈值
    left_cheek: 0.8,    // 左脸颊被遮挡的阈值
    right_cheek: 0.8,   // 右脸颊被遮挡的阈值
    chin_contour: 0.6   // 下巴被遮挡阈值
  },
  blur: 0.7,            // 模糊度阈值，小于0.7
  illumination: 40,     // 光照阈值，大于40
  angle: 20,            // 姿态角度阈值，小于20度
  minFaceSize: 100      // 最小人脸尺寸，100*100像素
}

// 获取Access Token
let accessToken: string | null = null
let tokenExpireTime: number = 0

/**
 * 获取百度API的Access Token
 */
async function getAccessToken(): Promise<string | null> {
  // 如果token未过期，直接返回缓存的token
  if (accessToken && Date.now() < tokenExpireTime) {
    return accessToken
  }

  try {
    const response = await fetch(BAIDU_FACE_CONFIG.TOKEN_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        grant_type: 'client_credentials',
        client_id: BAIDU_FACE_CONFIG.API_KEY,
        client_secret: BAIDU_FACE_CONFIG.SECRET_KEY
      })
    })

    const data = await response.json()
    
    if (data.access_token) {
      accessToken = data.access_token
      // token有效期通常是30天，这里设置29天过期
      tokenExpireTime = Date.now() + (29 * 24 * 60 * 60 * 1000)
      return accessToken
    } else {
      throw new Error('获取Access Token失败: ' + (data.error_description || '未知错误'))
    }
  } catch (error) {
    console.error('获取Access Token错误:', error)
    throw new Error('获取Access Token失败，请检查网络连接')
  }
}

/**
 * 将图片转换为Base64格式
 */
function imageToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      const result = reader.result as string
      // 移除data:image/jpeg;base64,前缀
      const base64 = result.split(',')[1]
      resolve(base64)
    }
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

/**
 * 人脸质量检测
 */
function checkFaceQuality(quality: {
  occlusion?: {
    left_eye?: number
    right_eye?: number
    nose?: number
    mouth?: number
    left_cheek?: number
    right_cheek?: number
    chin_contour?: number
  }
  blur?: number
  illumination?: number
  completeness?: number
}): { isValid: boolean; message: string } {
  const { occlusion, blur, illumination, completeness } = quality

  // 检查遮挡
  if (occlusion) {
    const occlusionThresholds = QUALITY_THRESHOLDS.occlusion
    for (const [key, threshold] of Object.entries(occlusionThresholds)) {
      const occlusionValue = occlusion[key as keyof typeof occlusion]
      if (occlusionValue !== undefined && occlusionValue > threshold) {
        return {
          isValid: false,
          message: `${key === 'left_eye' ? '左眼' : key === 'right_eye' ? '右眼' : key === 'nose' ? '鼻子' : key === 'mouth' ? '嘴巴' : key === 'left_cheek' ? '左脸颊' : key === 'right_cheek' ? '右脸颊' : '下巴'}被遮挡，请调整角度`
        }
      }
    }
  }

  // 检查模糊度
  if (blur !== undefined && blur >= QUALITY_THRESHOLDS.blur) {
    return {
      isValid: false,
      message: '图片模糊，请保持稳定并重新拍摄'
    }
  }

  // 检查光照
  if (illumination !== undefined && illumination < QUALITY_THRESHOLDS.illumination) {
    return {
      isValid: false,
      message: '光线不足，请调整光线环境'
    }
  }

  // 检查人脸完整度
  if (completeness !== 1) {
    return {
      isValid: false,
      message: '人脸不完整，请确保人脸完全在画面内'
    }
  }

  return {
    isValid: true,
    message: '人脸质量检测通过'
  }
}

/**
 * 人脸检测和质量评估
 */
export async function detectFace(imageBase64: string): Promise<{
  success: boolean
  data?: {
    face_token: string
    location: {
      left: number
      top: number
      width: number
      height: number
      rotation: number
    }
    face_probability: number
    angle: {
      yaw: number
      pitch: number
      roll: number
    }
    quality: {
      occlusion: {
        left_eye: number
        right_eye: number
        nose: number
        mouth: number
        left_cheek: number
        right_cheek: number
        chin_contour: number
      }
      blur: number
      illumination: number
      completeness: number
    }
  }
  message: string
}> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }
    
    const response = await fetch(`${BAIDU_FACE_CONFIG.DETECT_URL}?access_token=${token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        image: imageBase64,
        image_type: 'BASE64',
        face_field: 'quality,angle,face_shape,landmark'
      })
    })

    const data = await response.json()
    
    // 添加调试日志
    console.log('百度API响应数据:', data)
    
    if (data.error_code) {
      return {
        success: false,
        message: `人脸检测失败: ${data.error_msg}`
      }
    }

    // 检查响应数据结构
    if (!data.result || !data.result.face_list || !Array.isArray(data.result.face_list)) {
      return {
        success: false,
        message: 'API响应数据格式错误，未找到人脸列表'
      }
    }

    if (data.result.face_num === 0 || data.result.face_list.length === 0) {
      return {
        success: false,
        message: '未检测到人脸，请确保人脸在画面中'
      }
    }

    if (data.result.face_num > 1 || data.result.face_list.length > 1) {
      return {
        success: false,
        message: '检测到多张人脸，请确保画面中只有一张人脸'
      }
    }

    const face = data.result.face_list[0]
    
    // 检查人脸数据完整性
    if (!face || !face.location || !face.angle || !face.quality) {
      return {
        success: false,
        message: '人脸数据不完整，请重新拍摄'
      }
    }
    
    // 检查人脸大小
    const { width, height } = face.location
    if (width < QUALITY_THRESHOLDS.minFaceSize || height < QUALITY_THRESHOLDS.minFaceSize) {
      return {
        success: false,
        message: '人脸太小，请靠近摄像头'
      }
    }

    // 检查姿态角度
    const { yaw, pitch, roll } = face.angle
    if (Math.abs(yaw) > QUALITY_THRESHOLDS.angle || 
        Math.abs(pitch) > QUALITY_THRESHOLDS.angle || 
        Math.abs(roll) > QUALITY_THRESHOLDS.angle) {
      return {
        success: false,
        message: '人脸角度过大，请正面面对摄像头'
      }
    }

    // 检查人脸质量
    const qualityCheck = checkFaceQuality(face.quality)
    if (!qualityCheck.isValid) {
      return {
        success: false,
        message: qualityCheck.message
      }
    }

    return {
      success: true,
      data: face,
      message: '人脸检测成功'
    }
  } catch (error) {
    console.error('人脸检测错误:', error)
    return {
      success: false,
      message: '人脸检测失败，请检查网络连接'
    }
  }
}

/**
 * 人脸特征提取（用于注册）
 */
export async function extractFaceFeature(imageBase64: string): Promise<{
  success: boolean
  data?: {
    face_token: string
    feature: string
    quality: {
      occlusion: {
        left_eye: number
        right_eye: number
        nose: number
        mouth: number
        left_cheek: number
        right_cheek: number
        chin_contour: number
      }
      blur: number
      illumination: number
      completeness: number
    }
    location: {
      left: number
      top: number
      width: number
      height: number
      rotation: number
    }
  }
  message: string
}> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }
    
    const response = await fetch(`${BAIDU_FACE_CONFIG.DETECT_URL}?access_token=${token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        image: imageBase64,
        image_type: 'BASE64',
        face_field: 'feature,quality,angle,face_shape,landmark'
      })
    })

    const data = await response.json()
    
    // 添加调试日志
    console.log('百度API响应数据:', data)
    
    if (data.error_code) {
      return {
        success: false,
        message: `特征提取失败: ${data.error_msg}`
      }
    }

    // 检查响应数据结构
    if (!data.result || !data.result.face_list || !Array.isArray(data.result.face_list)) {
      return {
        success: false,
        message: 'API响应数据格式错误，未找到人脸列表'
      }
    }

    if (data.result.face_num === 0 || data.result.face_list.length === 0) {
      return {
        success: false,
        message: '未检测到人脸，请确保人脸在画面中'
      }
    }

    const face = data.result.face_list[0]
    
    // 检查人脸数据完整性
    if (!face || !face.location || !face.quality) {
      return {
        success: false,
        message: '人脸数据不完整，请重新拍摄'
      }
    }
    
    // 检查人脸质量
    const qualityCheck = checkFaceQuality(face.quality)
    if (!qualityCheck.isValid) {
      return {
        success: false,
        message: qualityCheck.message
      }
    }

    return {
      success: true,
      data: {
        face_token: face.face_token,
        feature: face.feature,
        quality: face.quality,
        location: face.location
      },
      message: '特征提取成功'
    }
  } catch (error) {
    console.error('特征提取错误:', error)
    return {
      success: false,
      message: '特征提取失败，请检查网络连接'
    }
  }
}

/**
 * 人脸M:N搜索（推荐用于人脸登录）
 */
export async function searchFaces(imageBase64: string, groupIdList: string = 'user_faces'): Promise<{
  success: boolean
  data?: {
    faceNum: number
    faceList: Array<{
      faceToken: string
      location: {
        left: number
        top: number
        width: number
        height: number
        rotation: number
      }
      userList: Array<{
        groupId: string
        userId: string
        userInfo: string
        score: number
      }>
    }>
  }
  message: string
}> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }
    
    const response = await fetch(`${BAIDU_FACE_CONFIG.SEARCH_URL}?access_token=${token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        image: imageBase64,
        image_type: 'BASE64',
        group_id_list: groupIdList,
        max_face_num: 1,
        quality_control: 'LOW',
        liveness_control: 'NORMAL'
      })
    })

    const data = await response.json()
    
    // 添加调试日志
    console.log('百度API响应数据:', data)
    
    if (data.error_code) {
      return {
        success: false,
        message: `人脸搜索失败: ${data.error_msg}`
      }
    }

    // 检查响应数据结构
    if (!data.result || !data.result.face_list || !Array.isArray(data.result.face_list)) {
      return {
        success: false,
        message: 'API响应数据格式错误，未找到搜索结果'
      }
    }

    if (data.result.face_num === 0 || data.result.face_list.length === 0) {
      return {
        success: false,
        message: '未找到匹配的人脸，请先注册人脸'
      }
    }

    interface BaiduSearchUser { group_id: string; user_id: string; user_info: string; score: number }
    interface BaiduSearchFace {
      face_token: string
      location: { left: number; top: number; width: number; height: number; rotation: number }
      user_list: BaiduSearchUser[]
    }

    const face: BaiduSearchFace = data.result.face_list[0] as BaiduSearchFace
    const userList: BaiduSearchUser[] = face.user_list || []
    
    if (userList.length === 0) {
      return {
        success: false,
        message: '未找到匹配的用户，请先注册人脸'
      }
    }

    // 找到最高分的用户
    const bestMatch: BaiduSearchUser = userList.reduce((prev: BaiduSearchUser, current: BaiduSearchUser) => 
      (prev.score > current.score) ? prev : current
    )

    const threshold = 80 // 相似度阈值，可根据需要调整
    const isMatch = bestMatch.score >= threshold

    return {
      success: isMatch,
      data: {
        faceNum: data.result.face_num,
        faceList: (data.result.face_list as BaiduSearchFace[]).map((f: BaiduSearchFace) => ({
          faceToken: f.face_token,
          location: f.location,
          userList: (f.user_list as BaiduSearchUser[]).map((u: BaiduSearchUser) => ({
            groupId: u.group_id,
            userId: u.user_id,
            userInfo: u.user_info,
            score: u.score
          }))
        }))
      },
      message: isMatch ? `人脸匹配成功，相似度: ${bestMatch.score.toFixed(1)}分` : `人脸不匹配，最高相似度: ${bestMatch.score.toFixed(1)}分`
    }
  } catch (error) {
    console.error('人脸搜索错误:', error)
    return {
      success: false,
      message: '人脸搜索失败，请检查网络连接'
    }
  }
}

/**
 * 人脸比对（保留用于其他场景）
 */
export async function compareFaces(imageBase64: string, targetFaceToken: string): Promise<{
  success: boolean
  data?: {
    score: number
    threshold: number
  }
  message: string
}> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }
    
    const response = await fetch(`${BAIDU_FACE_CONFIG.MATCH_URL}?access_token=${token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify([
        {
          image: imageBase64,
          image_type: 'BASE64',
          face_field: 'feature'
        },
        {
          image: targetFaceToken,
          image_type: 'FACE_TOKEN'
        }
      ])
    })

    const data = await response.json()
    
    // 添加调试日志
    console.log('百度API响应数据:', data)
    
    if (data.error_code) {
      return {
        success: false,
        message: `人脸比对失败: ${data.error_msg}`
      }
    }

    // 检查响应数据结构
    if (!data.result) {
      return {
        success: false,
        message: 'API响应数据格式错误，未找到比对结果'
      }
    }

    const score = data.result.score || 0
    const threshold = 80 // 相似度阈值，可根据需要调整

    return {
      success: score >= threshold,
      data: {
        score,
        threshold
      },
      message: score >= threshold ? '人脸比对成功' : '人脸不匹配'
    }
  } catch (error) {
    console.error('人脸比对错误:', error)
    return {
      success: false,
      message: '人脸比对失败，请检查网络连接'
    }
  }
}

/**
 * 创建人脸库
 */
export async function createFaceSet(groupName: string): Promise<{
  success: boolean
  data?: {
    face_token: string
    location: {
      left: number
      top: number
      width: number
      height: number
      rotation: number
    }
  }
  message: string
}> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }
    
    const response = await fetch(`${BAIDU_FACE_CONFIG.FACE_SET_URL}/add?access_token=${token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        display_name: groupName,
        outer_id: groupName
      })
    })

    const data = await response.json()
    
    console.log('创建人脸库响应:', data)
    
    if (data.error_code) {
      return {
        success: false,
        message: `创建人脸库失败: ${data.error_msg}`
      }
    }

    return {
      success: true,
      data: data.result,
      message: '人脸库创建成功'
    }
  } catch (error) {
    console.error('创建人脸库错误:', error)
    return {
      success: false,
      message: '创建人脸库失败，请检查网络连接'
    }
  }
}

/**
 * 添加用户到人脸库
 */
export async function addUserToFaceSet(
  groupId: string, 
  userId: string, 
  userInfo: string, 
  imageBase64: string
): Promise<{
  success: boolean
  data?: {
    face_token: string
    location: {
      left: number
      top: number
      width: number
      height: number
      rotation: number
    }
  }
  message: string
}> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }
    
    const response = await fetch(`${BAIDU_FACE_CONFIG.FACE_USER_URL}/add?access_token=${token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        image: imageBase64,
        image_type: 'BASE64',
        group_id: groupId,
        user_id: userId,
        user_info: userInfo,
        quality_control: 'LOW',
        liveness_control: 'NORMAL'
      })
    })

    const data = await response.json()
    
    // 添加详细的调试日志
    console.log('=== 人脸注册调试信息 ===')
    console.log('请求URL:', `${BAIDU_FACE_CONFIG.FACE_USER_URL}/add?access_token=${token}`)
    console.log('请求参数:', {
      group_id: groupId,
      user_id: userId,
      user_info: userInfo,
      image_type: 'BASE64',
      image_length: imageBase64.length,
      quality_control: 'LOW',
      liveness_control: 'NORMAL'
    })
    console.log('百度云响应:', data)
    console.log('=== 调试信息结束 ===')
    
    if (data.error_code) {
      return {
        success: false,
        message: `添加用户失败: ${data.error_msg}`
      }
    }

    return {
      success: true,
      data: data.result,
      message: '用户添加成功'
    }
  } catch (error) {
    console.error('添加用户错误:', error)
    return {
      success: false,
      message: '添加用户失败，请检查网络连接'
    }
  }
}

/**
 * 从人脸库删除用户
 */
export async function deleteUserFromFaceSet(
  groupId: string, 
  userId: string
): Promise<{
  success: boolean
  data?: Record<string, unknown>
  message: string
}> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }
    
    const response = await fetch(`${BAIDU_FACE_CONFIG.FACE_USER_URL}/delete?access_token=${token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        group_id: groupId,
        user_id: userId
      })
    })

    const data = await response.json()
    
    console.log('删除用户响应:', data)
    
    if (data.error_code) {
      return {
        success: false,
        message: `删除用户失败: ${data.error_msg}`
      }
    }

    return {
      success: true,
      data: data.result,
      message: '用户删除成功'
    }
  } catch (error) {
    console.error('删除用户错误:', error)
    return {
      success: false,
      message: '删除用户失败，请检查网络连接'
    }
  }
}

/**
 * 获取人脸库用户列表
 */
export async function getFaceSetUserList(
  groupId: string, 
  start: number = 0, 
  length: number = 100
): Promise<{
  success: boolean
  data?: {
    user_list: Array<{
      user_id: string
      user_info: string
      ctime: string
    }>
  }
  message: string
}> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }
    
    const response = await fetch(`${BAIDU_FACE_CONFIG.FACE_USER_URL}/list?access_token=${token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        group_id: groupId,
        start,
        length
      })
    })

    const data = await response.json()
    
    console.log('获取用户列表响应:', data)
    
    if (data.error_code) {
      return {
        success: false,
        message: `获取用户列表失败: ${data.error_msg}`
      }
    }

    return {
      success: true,
      data: data.result,
      message: '获取用户列表成功'
    }
  } catch (error) {
    console.error('获取用户列表错误:', error)
    return {
      success: false,
      message: '获取用户列表失败，请检查网络连接'
    }
  }
}

/**
 * 获取某用户的人脸列表（face_token 列表）
 */
export async function getUserFaceList(
  groupId: string,
  userId: string
): Promise<{
  success: boolean
  data?: { face_list: Array<{ face_token: string; ctime: string }> }
  message: string
}> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }

    const response = await fetch(`${BAIDU_FACE_CONFIG.FACE_FACE_URL}/getlist?access_token=${token}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ group_id: groupId, user_id: userId })
    })

    const data = await response.json()

    if (data.error_code) {
      return { success: false, message: `获取人脸列表失败: ${data.error_msg}` }
    }

    return { success: true, data: data.result, message: '获取人脸列表成功' }
  } catch (error) {
    console.error('获取人脸列表错误:', error)
    return { success: false, message: '获取人脸列表失败，请检查网络连接' }
  }
}

/**
 * 删除某个用户的一张具体人脸（通过 face_token）
 */
export async function deleteFaceFromUser(
  groupId: string,
  userId: string,
  faceToken: string
): Promise<{ success: boolean; data?: Record<string, unknown>; message: string }> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }

    const response = await fetch(`${BAIDU_FACE_CONFIG.FACE_FACE_URL}/delete?access_token=${token}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ group_id: groupId, user_id: userId, face_token: faceToken })
    })

    const data = await response.json()

    if (data.error_code) {
      return { success: false, message: `删除人脸失败: ${data.error_msg}` }
    }

    return { success: true, data: data.result, message: '人脸删除成功' }
  } catch (error) {
    console.error('删除人脸错误:', error)
    return { success: false, message: '删除人脸失败，请检查网络连接' }
  }
}

/**
 * 查询人脸库组列表
 */
export async function getFaceSetList(): Promise<{
  success: boolean
  data?: {
    face_set_list: Array<{
      face_set_id: string
      display_name: string
      outer_id: string
      ctime: string
    }>
  }
  message: string
}> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }
    
    const response = await fetch(`${BAIDU_FACE_CONFIG.FACE_SET_URL}/list?access_token=${token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        start: 0,
        length: 100
      })
    })

    const data = await response.json()
    
    console.log('=== 查询人脸库组列表 ===')
    console.log('百度云响应:', data)
    console.log('=== 查询结束 ===')
    
    if (data.error_code) {
      return {
        success: false,
        message: `查询失败: ${data.error_msg}`
      }
    }

    return {
      success: true,
      data: data.result,
      message: `查询成功，共找到 ${data.result?.face_set_list?.length || 0} 个人脸库组`
    }
  } catch (error) {
    console.error('查询人脸库组错误:', error)
    return {
      success: false,
      message: '查询失败，请检查网络连接'
    }
  }
}

/**
 * 查询人脸库用户列表（用于调试）
 */
export async function queryFaceSetUsers(groupId: string = 'user_faces'): Promise<{
  success: boolean
  data?: {
    user_list: Array<{
      user_id: string
      user_info: string
      ctime: string
    }>
  }
  message: string
}> {
  try {
    const token = await getAccessToken()
    if (!token) {
      throw new Error('无法获取Access Token')
    }
    
    const response = await fetch(`${BAIDU_FACE_CONFIG.FACE_USER_URL}/list?access_token=${token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        group_id: groupId,
        start: 0,
        length: 100
      })
    })

    const data = await response.json()
    
    console.log('=== 查询人脸库用户列表 ===')
    console.log('请求参数:', { group_id: groupId, start: 0, length: 100 })
    console.log('百度云响应:', data)
    console.log('=== 查询结束 ===')
    
    if (data.error_code) {
      return {
        success: false,
        message: `查询失败: ${data.error_msg}`
      }
    }

    return {
      success: true,
      data: data.result,
      message: `查询成功，共找到 ${data.result?.user_list?.length || 0} 个用户`
    }
  } catch (error) {
    console.error('查询人脸库错误:', error)
    return {
      success: false,
      message: '查询失败，请检查网络连接'
    }
  }
}

/**
 * 将File对象转换为Base64
 */
export async function fileToBase64(file: File): Promise<string> {
  return imageToBase64(file)
}

export { QUALITY_THRESHOLDS }
